<!DOCTYPE html>
<html>
<head lang="en">
    <meta charset="UTF-8">
    <title></title>
    <style>
        * {
            margin: 0;
            padding: 0;
        }

        #box {
            width: 300px;
            height: 280px;
            border-top: 20px solid #0f0;
            background-color: yellow;
            position: relative;
        }
    </style>
</head>
<body>
<button id="btn5">奔跑吧老范 500</button>
<button id="btn10">奔跑吧老范 1000</button>
<div id="box"></div>
<script>
    var btn5 = document.getElementById("btn5");
    var btn10 = document.getElementById("btn10");
    var box = document.getElementById("box");
    btn5.onclick = function () {
        animate(box, 500);
    }
    btn10.onclick = function () {
        animate(box, 1000);
    }
    function animate(element, target, interval) {
        clearInterval(element.timer);
        element.timer = setInterval(function () {
            var leader = element.offsetLeft;
            var step = 10;
            step = leader < target ? step : -step;
            if (Math.abs(leader - target) >= Math.abs(step)) {
                element.style.left = leader + step + "px";
            } else {
                element.style.left = target + "px";//手动放到目标位置
                clearInterval(element.timer);
            }
        }, interval)
    }
</script>
</body>
</html>